package Service;

import DAO.PurchaseDao;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PurchaseReceiverService {
    private List<PurchaseItem> purchaseItemList;
    private PurchaseDao purchaseDao;

    public List<PurchaseItem> getPurchaseItemList() {
        return purchaseItemList;
    }

    public void setPurchaseItemList(List<PurchaseItem> purchaseItemList) {
        this.purchaseItemList = purchaseItemList;
    }

    public PurchaseDao getPurchaseDao() {
        return purchaseDao;
    }

    public void setPurchaseDao(PurchaseDao purchaseDao) {
        this.purchaseDao = purchaseDao;
    }

    public float handle(String dataJson){
        purchaseItemList = jsonParser(dataJson);
        float totalPrice = 0;

        for (PurchaseItem item : purchaseItemList){
            String priceString = purchaseDao.getPriceList(item.bookId);
            float price = priceParser(priceString);
            int count = item.count;
            float item_priceCount = price * (float) count;
            totalPrice += item_priceCount;
        }
        return totalPrice;
    }

    public float priceParser(String priceString){
        float price = 0;
        if (priceString.trim().isEmpty()) {
            price = 1000;
        }else {
            String pattern = "(\\d+(.\\d+)?)";
            Pattern p = Pattern.compile(pattern);
            Matcher matcher = p.matcher(priceString);
            if (matcher.find())
                price = Float.parseFloat(matcher.group());
            else
                price = 1000;
            if (price == 0)
                price = 1000;
        }
        return price;
    }

    public List<PurchaseItem> jsonParser(String jsonSrc){
        List <PurchaseItem> itemList = new ArrayList<>();
        try {
            List<Map> list = (List) JSONUtil.deserialize(jsonSrc);
            for (Map<String,String> itemMap : list){
                PurchaseItem item = new PurchaseItem() ;
                item.bookId = itemMap.get("bookId");
                item.count = Integer.parseInt(itemMap.get("count"));
                itemList.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return itemList;
    }
    private class PurchaseItem{
        String bookId;
        int count;
    }
}
